#include "ADC.h"

unsigned short ADC_GetData(WifiIotAdcChannelIndex AdcChanne)
{
    unsigned short data = 0x00;
    if(AdcRead(AdcChanne, &data, WIFI_IOT_ADC_EQU_MODEL_8, WIFI_IOT_ADC_CUR_BAIS_DEFAULT, 0xFF)==0)
    {
        return data;
    }
    else
    {
        return 0x00;
    }
}

float ADC_GetVoltage(WifiIotAdcChannelIndex AdcChanne)
{
    return (float)ADC_GetData(AdcChanne) * 1.8 * 4 / 4096.0;
}

float ADC_GetSoilMoisture(void)
{
    uint32_t tempValue = 0;
	for(uint8_t t = 0; t < 10; t ++)
	{
		tempValue += ADC_GetData(WIFI_IOT_ADC_CHANNEL_6);
		hi_udelay(1000);
	}
	float avrgValue = 1.0 * tempValue / 10;
    uint16_t M0 = 2150;
    uint16_t M1 = 1250;
    if(avrgValue > M0) {avrgValue = M0;}
    if(avrgValue < M1) {avrgValue = M1;}
	float soilMoisture = (1.0*M0 - avrgValue) * 100.0 / (1.0*M0 - 1.0*M1);
	if(soilMoisture == 100) {soilMoisture = 99.9;}
	if(soilMoisture == 0) {soilMoisture = 0.1;}
    return soilMoisture;
}

float ADC_GetLiquidHeight(void)
{
    uint32_t tempValue = 0;
	for(uint8_t t = 0; t < 10; t ++)
	{
		tempValue += ADC_GetVoltage(WIFI_IOT_ADC_CHANNEL_1);
		hi_udelay(1000);
	}
	float avrgValue = 1.0 * tempValue / 10;
    float liquidHeight = (exp(0.0056 * avrgValue * 1000)) * 0.467;
	return liquidHeight;
}

float ADC_GetSmokeDensity(void)
{
    uint32_t tempValue = 0;
	for(uint8_t t = 0; t < 10; t ++)
	{
		tempValue += ADC_GetVoltage(WIFI_IOT_ADC_CHANNEL_4);
		hi_udelay(1000);
	}
	float avrgValue = 1.0 * tempValue / 10;
    float RS = 0.5 * (3.3 - avrgValue) / avrgValue;
    float R0 = 6.64;
    float PPM = pow(11.5428 * R0 / RS, 0.6549f);
    return PPM;
}
